<?php
namespace control;
// 产品维修
class aftermarketAssignClass extends adIndexClass
{
	private const title          = '维修派工';
	private const page           = 'aftermarketAssign';
	private const table          = 'aftermarket';
	private const tableTarget    = 'material';
	private const classify       = ['委外维修', '内部派工'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        $tr = [
            'orderNo'          => [
                'name'  => '单据编号',
                'width' => 200,
                'sort' => 1,
            ],
            'companyName' => [
                'name'  => "客户名称",
                'width' => 150,
            ],
            'name'  => [
                'name'  => "产品名称",
                'width' => 200,
            ],
            'code'  => [
                'name'  => "产品编码",
                'width' => 150,
            ],
            'repairer'  => [
                'name'  => "报修人",
                'width' => 150,
            ],
            'type'         => [
                'name'  => '故障类型',
                'width' => 100,
            ],
            'level'          => [
                'name'  => '故障等级',
                'width' => 200,
                'sort' => 1,
            ],
            'text'          => [
                'name'  => '故障描述',
                'width' => 180,
            ],
            'emergency'          => [
                'name'  => '紧急程度',
                'width' => 180,
            ]
        ];
        switch ($fun) {
            case 'partSearch':
                $tr = array_merge($tr,[
                    'classify'          => [
                        'name'  => '派工类型',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'processors'          => [
                        'name'  => '维修人',
                        'width' => 180,
                    ],
                    'commitTime'          => [
                        'name'  => '派工时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ]);
                break;
            default:
                $tr = array_merge($tr,[
                    'repairerTime'          => [
                        'name'  => '登记时间',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 180,
                    ]
                ]);
        }
        return $tr;
    }

    /**
     * 查询表单
     *
     * @param string $state
     * @return string
     */
    public function homeForm(string $state): string
    {
        $array = [
            [
                [
                    "单据编号" => text(array("name" => "orderNo")).hidden(['name' => 'state', 'value' => $state]),
                    "客户名称" => selectMultiple([
                        'table' => 'kehu',
                        'where' => " coid = '" . self::$coid . "' ",
                        "class" => 'width200',
                        'sqlField' => 'companyName',
                        'sqlId' => 'khid',
                        'name' => 'khid'
                    ]),
                    "产品名称" => text(array("name" => "eqName")),
                ],
                [
                    "产品编码"   => text(array("name" => "eqCode")),
                    "故障类型"   => select(["name" => "type", 'option' => explode('，', para('aftermarketType'))]),
                    '故障等级' => select(["name" => "level", 'option' => explode('，', para('aftermarketLevel'))]),
                ],
                [
                    '紧急程度' => select(["name" => "emergency", 'option' => explode('，', para('aftermarketEmergency'))]),
                ]
            ]
        ];
        switch ($state) {
            case '已登记':
                $array[0][2]['登记时间'] = text(['name' => 'repairerTime', 'laydate' => ['range' => '~', 'type' => 'datetime']]);
                break;
            case '已派工':
                $array[0][2]['派工时间'] = text(['name' => 'commitTime', 'laydate' => ['range' => '~', 'type' => 'datetime'],]);
                $array[0][2]['派工类型'] = select(["name" => "classify", 'option' => self::classify]);
                break;
        }
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已登记');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 查询条件
	 *
	 * @param string $state
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        $button = "";
		return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

    /*列表页-查询条件*/
    public function partOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('已派工');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	public function part(): string
	{
        $html = $this->partOptions(false);
        $button = "";
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	public function partSearch(): string
	{
		return $this->homeSearch();
	}

	/**
	 * 列表页-查询结果
	 *
	 * @return string
	 */
	public function homeSearch(): string
	{
		$state = $this->post('state') ?: '已登记';
		$equal = [
			'repairerStid' => $this->post('repairerStid'),
			'type'         => $this->post('type'),
			'level'        => $this->post('level'),
			'emergency'    => $this->post('emergency'),
			'classify'     => $this->post('classify'),
			'state'        => $state,
			// 'workFlow'     => self::workFlow,
			'coid'         => self::$coid,
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
			'text'    => $this->post('text'),
		];
		//生成查询语句
		$where = search([
			"="    => $equal,
			"like" => $like,
		]);
		//生成子查询语句
		$targetWhere = search([
			"like" => [
				'code' => $this->post('eqCode'),
				'name' => $this->post('eqName'),
			],
		]);
		if ($targetWhere) {
			$where .= " and targetId IN (SELECT id  FROM `" . self::tableTarget . "` WHERE 1=1 $targetWhere) ";
		}
		// 时间查询
		if ($this->post('repairerTime')) {
			$where .= self::timeComparison($this->post('repairerTime'), 'time', 'repairerTime');
		}
		if ($this->post('commitTime')) {
			$where .= self::timeComparison($this->post('commitTime'), 'time', 'commitTime');
		}
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate  = [
				"box"    => [
					"name" => "listId", "value" => $array['id'],
				],
				"detail" => [
					"title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')",
				],
			];
            $material  = query(self::tableTarget, " id = '$array[targetId]' ","name,code");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'companyName':
                        $kehu      = query('kehu', " khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case 'name':
                    case 'code':
                        $row[] = $material[$key];
                        break;
                    case 'processors':
                        $processors = ($array['classify'] === '内部派工') ? self::findStaff($array['processors']) : $array['processors'];
                        $row[] = $processors;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $li . "</form>" . $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$material  = query(self::tableTarget, " id = '$info[targetId]' ");
			$kehu      = query('kehu', " khid =  '$info[khid]' ", 'companyName');
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			if (in_array($info['state'], ['已登记', '已登记'])) {
				if ($this->power(self::page, 'registryCancel')) {
					$button[] = [
						"name" => "取消登记",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'registryCancel', "id" => $info['id']],
					];
				}
				if ($this->power('aftermarketAssign', 'assignOutside')) {
					$button[] = [
						"name" => "委外维修",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'assignOutside', "id" => $info['id']],
					];
				}
				if ($this->power('aftermarketAssign', 'assign')) {
					$button[] = [
						"name"  => "内部派工",
						"type"  => "弹出层",
						"cla"   => $this->get('cla'),
						"fun"   => "operate",
						"post"  => ["act" => 'assign', "id" => $info['id']],
						'style' => 'li-btn-blue-bg',
					];
				}
			}
			if ($info['state'] === '已派工') {
				if ($this->power('aftermarketAssignPart', 'assignCancel')) {
					$button[] = [
						"name" => "取消派工",
						"type" => "弹出层",
						"cla"  => $this->get('cla'),
						"fun"  => "operate",
						"post" => ["act" => 'assignCancel', "id" => $info['id']],
					];
				}
				if ($this->power('aftermarketAssignPart', 'done')) {
					$button[] = [
						"name"  => "填写结果",
						"type"  => "弹出层",
						"cla"   => $this->get('cla'),
						"fun"   => "operate",
						"post"  => ["act" => 'done', "id" => $info['id']],
						'style' => 'li-btn-blue-bg',
					];
				}
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']          = $this->tableShow(
                [
                    '基本信息' => [
                        [
                            "客户" => $kehu['companyName'],
                            "产品" => $material['code'] . ' - ' . $material['name'] . ' - ' . ($material['model']?:'无'),
                            "报修人"     => self::findStaff($info['repairer']) ?: $info['repairer'],
                            "报修人电话" => $info['repairerTel'],
                        ],
                        [
                            "报修时间"   => $info['repairerTime'],
                            "故障类型" => $info['type'],
                            "故障等级" => $info['level'],
                            "紧急程度" => $info['emergency'],
                        ],
                        [
                            "故障描述" => pre($info['text']),
                        ],
                        [
                            "故障图片" => fileUploadClass::showImg($info['id'], '故障图片'),
                        ],
                    ]
                ]
            );
			$tfield                = ($info['classify'] == '委外维修') ? '委外单位' : "维修部门";
			// 进度为派工时
			if (in_array($info['workFlow'], ['派工', '维修'])) {
                $data['html']          .= $this->tableShow(
                    [
                        '派工信息' => [
                            [
                                $tfield    => $info['processingDepartment'],
                                "维修人"   => ($info['classify'] == '委外维修') ? $info['processors'] : self::findStaff($info['processors']),
                                "派工时间" => $info['commitTime'],
                            ],
                            [
                                "处理意见" => $info['processingResult'],
                            ],
                        ]
                    ]
                );
			}
			// 进度为维修时
			if ($info['workFlow'] == '维修') {
                $data['html']          .= $this->tableShow(
                    [
                        '维修记录' => [
                            [
                                "维修日期"      => $info['repairDate'],
                                "维修时长（min）" => $info['repairTime'],
                                "维修结果"      => $info['repairResult'],
                            ],
                            [
                                "维修措施" => $info['repairMeasure'],
                            ],
                        ]
                    ]
                );
				// 关联领用单
				$tr[]   = ['配件编码', '名称', '规格型号', '单位', '数量', '单价（' . static::$unit . '）', '金额（' . static::$unit . '）', '备注'];
				$result = find([
					'table' => 'parts_inventory as p, parts_inventory_detail as d',
					'field' => 'd.*',
					'where' => " p.id = d.orderId AND p.classify=0 AND  p.state='已确认' AND p.sourceId = '{$info['id']}' ",
				]);
				foreach ($result['array'] as $array) {
					$parts    = query('material', " id = '$array[partsId]' ");
					if (static::isNull($parts['id'])) {
						continue;
					}
					// 减去退货部分
					$returnNum = static::total([
						'sql'   => "SELECT IFNULL(SUM(num), 0) AS total FROM `parts_inventory_detail` ",
						'where' => " `sourceTable` = 'parts_inventory_detail' AND `sourceId` IN (SELECT id FROM `parts_inventory` WHERE classify=0 AND  state='已确认' AND sourceId = '{$info['id']}' ) ",
					]);
					$price     = inventoryBalanceClass::unitPrice($parts['id']);
					$num       = $array['num'] - $returnNum;
					$money     = round($num * $price, 2);
					$tr[]      = [$parts['code'], $parts['name'], $parts['model'], $parts['unit'], $num, $price, $money, $array['text'],];
				}
                $data['html'] .= $this->detailList([
                    'title' => '配件领用',
                    'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'showSort' => true)),
                ]);
			}
            $data['html']          .= $this->tableShow(
                [
                    '系统信息' => [
                        [
                            "单据编号" => $info['orderNo'],
                            "创建人"   => self::findStaff($info['stid']),
                            "创建时间" => $info['time'],
                        ],
                        [
                            "更新时间" => $info['updateTime'],
                            "状态"     => $info['state'],
                        ],
                    ]
                ]
            );
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act    = $this->post('act') ?: '';
		$cla    = $this->post('cla') ?: $this->get('cla');
		$pwd    = '';
        $width = null;
		$height = null;
		$append = [];
		$word   = false;
		$page = self::page;
		// 需要密码
		switch ($act) {
			case 'assignOutside':
				$act      = 'assignOutside';
				$msg      = '委外维修';
				$title    = '';
				$function = 'changeWorkFlow';
				$append   = [
					[
						must . '维修单位' => text(['name' => 'processingDepartment']),
					],
					[
						must . '维修人' => text(['name' => 'processors']),
					],
					[
						must . '维修人联系电话' => text(['name' => 'processorsTel']),
					],
					[
						'处理意见：' => textarea(['name' => 'processingResult', 'class' => 'width300']),
					],
				];
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$height   = 360;
				$word     = true;
				break;
			case 'assign':
				$act      = 'assign';
				$msg      = '内部派工';
				$title    = '';
				$function = 'changeWorkFlow';
				$append   = [
					[
						must . '维修人员' => selectMultiple(['table' => 'staff', "title" => '请选择', 'sqlField' => 'name', 'sqlId' => 'stid', 'name' => 'processors']),
					],
					[
						'处理意见：' => textarea(['name' => 'processingResult', 'class' => 'width300']),
					],
				];
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$height   = 270;
				$word     = true;
				break;
			case 'assignCancel':
			    $page = 'aftermarketAssignPart';
				$act      = 'assignCancel';
				$msg      = '取消派工';
				$title    = '是否取消维修单的派工？';
				$function = 'changeWorkFlow';
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$word     = true;
				break;
			case 'done':
                $page = 'aftermarketAssignPart';
				$act      = 'done';
				$msg      = '填写结果';
				$title    = '';
				$function = 'changeWorkFlow';
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				$word     = true;
				$info     = query(self::table, " id = '{$this->post('id')}' ");
				$append   = [
					[
						must . '维修日期' => text(['name' => 'repairDate', 'class' => 'text', 'value' => $info['repairDate'] ?: $this->date, 'laydate' => ['type' => 'date']]),
						'维修时长：' => text(['name' => 'repairTime', 'class' => 'text', 'unit' => 'min', 'value' => $info['repairTime']]),
					],
					[
						'维修费用：' => text(['name' => 'repairFee', 'class' => 'text', 'value' => $info['repairFee']]),
						'维修结果：' => text(['name' => 'repairResult', 'class' => 'text', 'value' => $info['repairResult']]),
					],
					[
						'维修措施：' => textarea(['name' => 'repairMeasure', 'value' => $info['repairMeasure']]),
					],
				];
				$height   = 300;
                $width = 800;
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, detailForm';
				$power    = '';
				break;
		}
		if (!$this->power($page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $cla . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
				'append'   => $append,
				'height'   => $height,
				'width'   => $width,
				'hidden'   => hidden(['name' => 'act', 'value' => $act]) . hidden(['name' => 'cla', 'value' => $cla]),
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 处理结果
	 *
	 * @return bool|string
	 */
	public function changeWorkFlow(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$act   = $this->post('act') ?: '';
		$cla   = $this->post('cla') ?: $this->get('cla');
		$json  = [];
		/*if (!$this->power(self::page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} else*/
        if (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			switch ($act) {
				case 'registryCancel':
					$opt        = '取消登记';
					$field      = [
						'workFlow' => '登记',
						'state'    => '草稿',
					];
					$annotation = [
						'workFlow' => '进度',
						'state'    => '状态',
					];
					$rules      = [
						'workFlow' => 'required',
						'state'    => 'required',
					];
					break;
				case 'assignOutside':
					$opt        = '委外维修';
					$field      = [
						'processingDepartment' => $this->post('processors'),
						'processors'           => $this->post('processors'),
						'processorsTel'        => $this->post('processorsTel'),
						'processingResult'     => $this->post('processingResult'),
						'commitTime'           => $this->date,
						'classify'             => '委外维修',
						'workFlow'             => '派工',
						'state'                => '已派工',
					];
					$annotation = [
						'processingDepartment' => '维修单位',
						'processors'           => '维修人员',
						'processorsTel'        => '维修人电话',
						'processingResult'     => '处理意见',
						'workFlow'             => '进度',
						'state'                => '状态',
					];
					$rules      = [
						'processingDepartment' => 'required',
						'processors'           => 'required',
						'processorsTel'        => 'required|tel',
						'workFlow'             => 'required',
						'state'                => 'required',
					];
					break;

				case 'assign':
					$opt        = '内部派工';
					$field      = [
						'processingDepartment' => self::findStaffDepartment($this->post('processors')),
						'processors'           => $this->post('processors'),
						'processingResult'     => $this->post('processingResult'),
						'commitTime'           => $this->date,
						'classify'             => '内部派工',
						'workFlow'             => '派工',
						'state'                => '已派工',
					];
					$annotation = [
						'processingDepartment' => '维修部门',
						'processors'           => '维修人员',
						'processingResult'     => '处理意见',
						'workFlow'             => '进度',
						'state'                => '状态',
					];
					$rules      = [
						'processingDepartment' => 'required',
						'processors'           => 'required',
						'workFlow'             => 'required',
						'state'                => 'required',
					];
					break;
				case 'assignCancel':
					$opt        = '取消派工';
					$field      = [
						'processingDepartment' => '',
						'processors'           => '',
						'processingResult'     => '',
						'commitTime'           => '',
						'workFlow'             => '派工',
						'state'                => '已登记',
					];
					$annotation = [
						'workFlow' => '进度',
						'state'    => '状态',
					];
					$rules      = [
						'workFlow' => 'required',
						'state'    => 'required',
					];
					break;
				case 'done':
					$opt        = '完成';
					$field      = [
						'workFlow'      => '维修',
						'repairDate'    => $this->post('repairDate'),
						'repairTime'    => $this->post('repairTime'),
						'repairResult'  => $this->post('repairResult'),
						'repairFee'     => $this->post('repairFee'),
						'repairMeasure' => $this->post('repairMeasure'),
						'state'         => '已完成',
					];
					$annotation = [
						'repairDate' => '维修日期',
						'workFlow'   => '进度',
						'state'      => '状态',
					];
					$rules      = [
						'repairDate' => 'required|date',
						'workFlow'   => 'required',
						'state'      => 'required',
					];
					break;
				default:
					$json['warn'] = "未知操作";
					goto resp;
			}
			// 校验是否符合规则
			$vt     = new \verify();
			$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
			if ($result === false) {
				$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
				goto resp;
			}
			foreach ($array as $id) {
				$where = " id = '$id' AND coid = '" . self::$coid . "' ";
				$info  = query(self::table, $where);
				if (static::isNull($info['id'])) {
					continue;
				}
				$warn = static::update([
					'table' => self::table,
					'field' => $field,
					'where' => $where,
				]);
				if (in_array($warn, ['更新成功', '新增成功'])) {
					$text .= "管理员{$this->control['name']}{$opt}了一条" . self::title . "：ID【{$id}】<br>";
					$x++;
				}
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "处理了{$x}条" . self::title;
			$json['warn']     = 2;
		}
		resp:
		return json_encode($json, 320);
	}

}
